<?php
/**
 * 附件 - JBlog
 * 
 * @copyright (c) 2008-2010 JBlog (www.lisijie.org)
 * @author lisijie <lisijie86@gmail.com>
 * @version $Id: attach.php 337 2010-04-15 16:23:24Z lisijie86 $
*/

$fileid = intval($get['id']);

!$fileid && exit();

//防盗链
if ( ! config('remote_open') ) {
	$allow_host = explode(',',config('allow_domain'));
	$referer = parse_url($_SERVER['HTTP_REFERER']);
	if (!in_array($referer['host'], $allow_host)) {
		header('Content-Encoding: none');
		header('Content-Type: image/gif');
		header('Content-Disposition: inline; filename="open_denied.gif"');
		$fp=fopen(JBLOG_ROOT.'images/open_denied.gif','rb');
		fpassthru($fp);
		fclose($fp);
		exit();
	}
}

$file = $db->fetch_one_array("SELECT id,filepath,filetype,originalname,filesize,dateline 
FROM ".tname('attach')." WHERE id = '$fileid'");

if (!$file) {
	die('file_not_exist');
} else {
	//通过判断getimagesize取出的图片信息是否存在类型标记和色彩位深来防止伪造。
	$isimage = false;
	if (stristr($file['filetype'],'image')) {
		$imginfo = @getimagesize($file['filepath']);
		if ($imginfo[2] && $imginfo['bits']) {
			$isimage = true;
		}
		unset($imginfo);
	}
	//附件读取形式，inline直接读取，attachment下载到本地
	$disposition = $isimage ? 'inline' : 'attachment';
	//附件才统计下载次数
	if ( $disposition == 'attachment' ) {
		$d = false;
		if ( $attachmemts = get_cookie('attachmemts') ) {
			$idarr = explode(',', $attachmemts);
			if ( in_array($fileid, $idarr) ) {
				$d = true;
			}
		}
		if (!$d) {
			$db->query("UPDATE ".tname('attach')." SET downloads = downloads + 1 WHERE id = '$fileid'");
			$attachments .= empty($attachments) ? $fileid : ','.$fileid;
			set_cookie('attachmemts', $attachments);
		}	
	}
	$file['filetype'] = $file['filetype'] ? $file['filetype'] : 'application/octet-stream';
	$file['filepath'] = JBLOG_ROOT.$file['filepath'];
	$file['originalname'] = basename($file['originalname']);
	if (is_readable($file['filepath'])) {
		ob_end_clean();
		header('Cache-control: max-age=31536000');
		header('Expires: ' . get_date(NOW + 31536000,'D, d M Y H:i:s') . ' GMT');
		header('Last-Modified: ' . get_date($file['dateline'],'D, d M Y H:i:s') . ' GMT');
		header('Content-Encoding: none');
		header('Content-type: '.$file['filetype']);
		header('Content-Disposition: '.$disposition.'; filename='.urlencode($file['originalname']));
		header('Content-Length: '.$file['filesize']);
		$fp = fopen($file['filepath'], 'rb'); 
		fpassthru($fp);
		fclose($fp);
		exit;
	} else {
		exit('file read failure!');
	}
}
?>